package sqlToGUI.sqlRetrievalAlgorithms.motor;


import java.sql.SQLException;
import java.sql.Timestamp;

import sqlToGUI.charts.helperUtilities.TelemetryDataEntry;
import sqlToGUI.sqlRetrievalAlgorithms.AbstractDataRetrievalAlgorithm;
import sqlToGUI.sqlRetrievalAlgorithms.SQLDataRetrievalAlgorithm;


public class Alg_MotorCurrent extends AbstractDataRetrievalAlgorithm  
	implements SQLDataRetrievalAlgorithm {

	
	/**Class constructor */
	public Alg_MotorCurrent(TelemetryDataEntry[] list){
		super();
		this.list = list;
	}
	
	/**Access the database and update data in the buffer */
	@SuppressWarnings("deprecation")
	public void updateData(){
		
		/**Use the timer for accessing the buttom rows with
		 * the most recent timestamp - set this value back a few 
		 * seconds to avoid returning null values for results
		 * that have not yet entered the database */
		Timestamp ts =  new Timestamp(super.timeNow.getTimeInMillis());
		ts.setSeconds(ts.getSeconds()-setBack);
		
		/**Execute the query */
		try {
			super.statement.clearBatch();
			super.query = "SELECT A1.VoltageIn1 FROM SolarArray A1 " + " " +
			        "WHERE A1.Timestamp IN " +
				       "(SELECT cast(timestamp as char) timestamp " +
					   "FROM SolarArray " +
						   "WHERE timestamp > '" 
					   + ts.toString().substring(0, 19) + "');";

			super.rs = super.statement.executeQuery(super.query);
			rs.next();
			list[0].updateData(0, super.rs.getDouble(1));
			super.rs.close();

			super.query = "SELECT A1.VoltageOut1 FROM SolarArray A1 " + " " +
			        "WHERE A1.Timestamp IN " +
				       "(SELECT cast(timestamp as char) timestamp " +
					   "FROM SolarArray " +
						   "WHERE timestamp > '" 
					   + ts.toString().substring(0, 19) + "');";
			
			super.rs = super.statement.executeQuery(super.query);
			rs.next();
			list[1].updateData(0, super.rs.getDouble(1));
			super.rs.close();
			
		} catch (SQLException e) {
			System.out.println("Alg_ArrayVoltage: Failed to read data " +
					"from database after query failure ");
			list[0].updateData(0, 0);
			list[1].updateData(0, 0);
			System.out.println("Query: " + query);
		} catch (NullPointerException e) {
			System.out.println("Alg_ArrayVoltage: Failed to read data " +
			"from database or no input found ");
			list[0].updateData(0, 0);
			list[1].updateData(0, 0);
		} catch (ArrayIndexOutOfBoundsException e) {
			System.out.println("Alg_ArrayVoltage: More or less buffers" +
					" have been expected for the algorithm");
			list[0].updateData(0, 0);
			list[1].updateData(0, 0);
		}	
	}
}
